from django.contrib.auth import logout
from django.contrib.auth.hashers import make_password
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.views import refresh_jwt_token
from sqlalchemy.sql.functions import user

from apps.users.models import User
from apps.users.serializers import UserModelSerializer, UserCreateSerializer, UserUpdateSerializer
from apps.utils.paginate import PageSet


class UserAPIView(ModelViewSet):
    """用户管理-增删改查"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer
    pagination_class = PageSet
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('username', 'phone', 'email',)
    ordering_fields = ('date_joined', 'last_login',)
    filter_fields = ('username',)

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'create':
            return UserCreateSerializer
        elif self.action == 'update':
            return UserUpdateSerializer
        return UserModelSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if User.objects.filter(username=request.data['username']):
            return Response(data='用户名已存在', status=200)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['password'] = make_password(serializer.validated_data['password'])
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        for query in queryset:
            query.is_superuser = 1 if query.is_superuser else 0
        if not self.request.user.is_superuser:
            queryset = queryset.filter(id=self.request.user.id)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        password = request.data.get("password", None)
        # password = request.data.get("password", None)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        if password is not None:
            serializer.validated_data['password'] = make_password(password)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        # if password is not None:
        #     print(password)
        #     request.user.make_password(password[0])
        #     request.user.save()
        return Response(serializer.data)


class LogoutView(APIView):
    permission_classes = []

    def get(self, request, *args, **kwargs):
        logout(request)
        return Response(status=status.HTTP_200_OK)
